package com.example.administrator.namelist;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDelListener{
    private ListView nameList;
    //动态数组
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    //显示搜索结果的数组
    private ArrayList<Student> searchResultList = new ArrayList<>();
    //自定义适配器
    private StuAdapter adapter;
    private Button addStu;
    private EditText editKey;
    private Button searchStu;
    //判断是否是结果列表
    private Boolean isResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("通讯录");

        initStuList();

        initStuAdapter();

        initListView();

        initAdd();

        initSearch();
    }

    //搜索学生
    private void initSearch() {
        editKey = findViewById(R.id.editKey);
        searchStu = findViewById(R.id.btn_search);

        //搜索点击事件
        searchStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取用户输入的关键字
                String key = editKey.getText().toString();
                //判断是否符合条件并且进行搜索
                search(studentArrayList,key);
                //是哪个数组进行显示
                adapter.changeData(searchResultList);
                isResult = true;
            }
        });

        //搜索框的自动搜索
        editKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = editKey.getText().toString();
                search(studentArrayList,key);
                adapter.changeData(searchResultList);
                isResult = true;
            }
        });
    }

    private void search(ArrayList<Student> studentArrayList, String key) {
        //每次搜索要对结果列表进行清除，否则会出现叠加的情况
        searchResultList.clear();
        //便利找寻符合条件的
        for(int i=0; i<studentArrayList.size(); i++){
            Student s = studentArrayList.get(i);
            if(s.getName().contains(key) || String.valueOf(s.getName()).equals(key)){
                //添加到结果列表中
                searchResultList.add(s);
            }
        }
    }

    //添加学生
    private void initAdd() {
        addStu = findViewById(R.id.btn_add);
        addStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.e("MainActivity", "requestCode = " + requestCode +"   resultCode = " + resultCode);

        //若不改操作，直接退回，需要判断是否有data
        if(data == null){
            return;
        }

        //由于一个活动中可以有多个resultCode进入不同的活动页面，需要进行判断
        if(resultCode == 2001){
            String number = data.getStringExtra("NUMBER");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);
            int imgId = data.getIntExtra("IMG",R.drawable.s1);

            Student s = new Student(number,imgId,name,age);
            studentArrayList.add(s);

            //数据的更新操作
            adapter.notifyDataSetChanged();
        }else if(resultCode == 3001){
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);
            int imgId = data.getIntExtra("IMG",R.drawable.s1);
            String number = data.getStringExtra("NUMBER");

            for (int i=0; i<studentArrayList.size(); i++){
                Student s = studentArrayList.get(i);
                if(s.getNumber().equals(number)){
                    //修改显示的数据
                    s.setName(name);
                    s.setAge(age);
                    s.setImgId(imgId);
                }
            }

            //重新搜索
            String key = editKey.getText().toString();
            search(studentArrayList,key);
            adapter.changeData(searchResultList);
            isResult = true;
        }
    }

    //初始化列表
    private void initListView() {
        nameList = findViewById(R.id.nameList);
        nameList.setAdapter(adapter);

        //ListView的点击事件
        nameList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Student s = studentArrayList.get(i);

                if(isResult){
                    s = searchResultList.get(i);
                }

                Toast.makeText(MainActivity.this,
                        "姓名："+ s.getName() + "    年龄：" + s.getAge(),
                        Toast.LENGTH_SHORT).show();

                //向下一个活动传递数据
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,EditActivity.class);
                intent.putExtra("NAME",s.getName());
                intent.putExtra("AGE",s.getAge());
                intent.putExtra("IMG",s.getImgId());
                intent.putExtra("NUMBER",s.getNumber());
                startActivityForResult(intent,1002);
            }
        });
    }

    //初始化适配器
    private void initStuAdapter() {
        adapter = new StuAdapter(MainActivity.this,studentArrayList,
                MainActivity.this);
    }

    //初始化学生列表并学生添加到列表中
    private void initStuList() {
        Student s1 = new Student("181001",R.drawable.s1,"小一",18);
        Student s2 = new Student("181002",R.drawable.s2,"小二",19);
        Student s3 = new Student("181003",R.drawable.s3,"小三",20);
        Student s4 = new Student("181004",R.drawable.s4,"小四",21);
        Student s5 = new Student("181005",R.drawable.s5,"小五",22);

        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);
        studentArrayList.add(s4);
        studentArrayList.add(s5);
    }

    //删除
    @Override
    public void del(String number) {
        for(int i=0; i<studentArrayList.size(); i++){
            Student s = studentArrayList.get(i);

            if(s.getNumber().equals(number)){
                studentArrayList.remove(i);
            }
        }

        for(int i=0; i<searchResultList.size(); i++){
            Student s = searchResultList.get(i);

            if(s.getNumber().equals(number)){
                searchResultList.remove(i);
            }
        }

        adapter.notifyDataSetChanged();
    }
}
